﻿using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
using RabbitMQ_Common;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RabbitMQ_Proider.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DirectSendController : ControllerBase
    {
        // GET: api/<DirectSendController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            using (var connection = RabbitMQHelper.GetConnection())
            {
                using (var channel = connection.CreateModel())//创建信道，通信管道
                {
                    //声明交换机
                    channel.ExchangeDeclare("direct_exchange", "direct");

                    //创建队列
                    var queue = "directtest1";
                    channel.QueueDeclare(queue, false, false, false, null);//durable等于true时就是消息持久化，用户重启不丢消息
                    var queue2 = "directtest2";
                    channel.QueueDeclare(queue2, false, false, false, null);
                    var queue3 = "directtest3";
                    channel.QueueDeclare(queue3, false, false, false, null);
                    //绑定交换机,指定routingKey
                    string[] routingKeyList = new string[] { "red", "gre", "yell" };
                    channel.QueueBind(queue, "direct_exchange", routingKeyList[0]);
                    channel.QueueBind(queue2, "direct_exchange", routingKeyList[1]);
                    channel.QueueBind(queue3, "direct_exchange", routingKeyList[2]);
                    //没绑定交换机，但由于rabbitmq有默认交换机
                    for (var i = 0; i < 10; i++)
                    {
                        foreach(var row in routingKeyList)
                        {
                            //指定发送routingKey
                            string message = "测试1" + i;
                            var body = Encoding.UTF8.GetBytes(message);
                            channel.BasicPublish("direct_exchange", row, null, body);
                        }
                        
                    }


                }
            }
            return new string[] { "ok" };
        }

       
    }
}
